let express = require("express");
let router = express.Router();
let { AdvertisementModel } = require("../db/db");
const fs = require('fs')
let Objectid = require("mongodb").ObjectId;

router.get("/ment", async function (req, res) {
  let data = await AdvertisementModel.find({});
  res.send({ data: data, code: 200 });
});

router.post("/ment", async function (req, res) {
  let body = req.body;
  await AdvertisementModel.create({ ...body });
  res.send({ code: 200, message: "创建成功" });
});

router.put("/ment", async function (req, res) {
  let data = req.body;
  let id = Objectid(data["id"]);
  await AdvertisementModel.find({ _id: id }).update({ $set: data });
  res.send({ code: 200 });
});

router.delete("/ment", async function (req, res) {
  let id = Objectid(req.query.id);
  fs.unlinkSync(req.query.imageUrl.slice(1)) // 同时删除对应图片
  await AdvertisementModel.findByIdAndDelete({ _id: id }, function (err, data) {
    if (!err) {
      res.json({ message: "删除成功", code: 200 });
    }
  });
});

module.exports = router;
